//index.js
//获取应用实例
const app = getApp()
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast'
import { timeDifference } from '../../utils/util'
import dayjs from '../../miniprogram_npm/dayjs/index'
import api from '../../utils/api'
Page({
  data: {
    maskShow:false,
    mainActiveIndex: 0,
    activeId: null,
    currcity:'北京',
    items:[],

    hotlist:[],//热门榜单
    likelist:[],//猜你喜欢
    searchlist:[],//搜索滚动

    imageBaseURL: app.imageBaseURL,
    imageResizeParams: app.imageResizeParams,
    swiper_banner: [], 
    indicatorDots: true,
    vertical: false,
    autoplay: true,
    interval: 2000,
    duration: 500,
    findmore:[
      
    ],//发现更多
  },
  //搜索页
  navSearch(e){
    wx.navigateTo({
      url: '/pages/find_search/index?name=' + e.currentTarget.dataset.name
    })
  },
  //排行榜
  goCharts(){
    wx.navigateTo({
      url: '/pages/index_charts/index',
    })
  },
  //地区选择点击
  onClickNav({ detail = {} }) {
    this.setData({
      mainActiveIndex: detail.index || 0,
    });
	app.globalData.firstAreaIndex = detail.index
  },
  onClickItem({ detail = {} }) {
	console.log(detail)
    const activeId = this.data.activeId === detail.id ? null : detail.id;
    let currcity = detail.text
	if( !activeId ){
		currcity = this.data.items[this.data.mainActiveIndex].text
	}
    this.setData({ activeId, maskShow:false, currcity });
    app.globalData.address.city = currcity
	app.globalData.firstAreaId = activeId
	  this.query()
  },
  //区域显示/隐藏
  showRegion(){
	let _this = this
	console.log(_this.data.currcity)
	let mainActiveIndex = 0, activeId = null
	this.data.items.find(function(item,index) {
		console.log(item)
		if( _this.data.currcity.indexOf(item.text)>-1 ){
			mainActiveIndex = index
			activeId = null
			return true;
		}
		else{
			return item.children && item.children.find(function(item1,idx){
				if( _this.data.currcity.indexOf(item1.text)>-1 ){
					mainActiveIndex = index
					activeId = item1.id
					return true
				}else{
					return false
				}
			})
		}
	});
	console.log( mainActiveIndex,activeId)
		
    this.setData({ 
      maskShow:true, mainActiveIndex, activeId
     });
  },
  hideRegion(){
    this.setData({ 
      maskShow:false
     });
  },
  /* 阻止冒泡事件 */
  stopPropagation(){
    return;
  },
  //跳转地图页
  gomappage(){
    wx.navigateTo({
      url: '/pages/map/index',
    })
  },

  // 获取地址
  async getAddress () {
    const {recode, result, message} = await api.send({flag: 'v2index_city'})
    if(recode === 'SUCC') {
      let areadata=[]
      let linecity = ["北京市","上海市","天津市","重庆市","兵团"]
      result.forEach(item => {
        let obj = {}
        obj['text'] = item.provice_name
        obj['id'] = item.id

        let retcity = linecity.filter((item)=>{
          return item.indexOf(obj.text)>-1
        })
        if( retcity.length>0 ){
          obj['children'] = [{id:obj.id,text:obj.text}]
        }else{
          if( item.city && item.city.length>0 ){
            obj['children'] = []
            for(let p in item.city ){
              obj['children'].push({id:item.city[p].id,text:item.city[p].city_name})
            }
          }
        }
        areadata.push(obj)
      })
      app.globalData.addrList = areadata
      this.setData({items: areadata})
    }else {
      // Toast(message)
    }
  },

  //banner
  async getBanner () {
    let data={}
    data['flag'] = 'v2index'
    data['page'] =1
    data['pagesize'] = 50
    data['cityName'] = this.data.currcity
    const {recode, result, message} = await api.send(data)
    if(recode === 'SUCC') {
      result.banner.forEach((item)=>{
        item.img = api.checkurl(item.img)
      })
      this.setData({
        bannerlist:result.banner, 
      })
    }else {
      this.setData({
        bannerlist:[],
      })
      // Toast(message)
    }
  },
  //热榜
  async getHot () {
    let data={}
    data['flag'] = 'ranking_top_three'
    data['cityName'] = this.data.currcity
    data['citycode'] =app.globalData.firstAreaId
    data['status'] = 1
   
    const {recode, result, message} = await api.send(data)
    if(recode === 'SUCC') {
      result.forEach((item,index) => {
        item.imgurl[0] = api.checkurl(item.imgurl[0])
      })
      let hotlist = result.slice(0,3)
      console.log(result)
      this.setData({
        hotlist
      }) 
    }else {
      // Toast(message)
    }
  },


  //搜索滚动数据
  async getSearch (){
    let data={}
    data['flag'] = 'search_list'
    data['cityName'] = this.data.currcity
    const {recode, result, message} = await api.send(data)
    if(recode === 'SUCC') {
      this.setData({
        searchlist:result,
      })
    
    }else {
      this.setData({
        likelist:[],
      })
      // Toast(message)
    }
  },

  //正在报名
  async getSiging () {
    let data={}
    data['flag'] = '_active_apply_list'
    data['page'] =1
    data['pagesize'] = 5
    data['cityName'] = this.data.currcity
    const {recode, result, message} = await api.send(data)
    if(recode === 'SUCC') {
      result && result.forEach((item,index) => {
        item.imgurl[0] = this.loadImg(item.imgurl[0])
      })
      this.setData({
        activelist:result,
      })
    }else {
      this.setData({
        activelist:[],
      })
      // Toast(message)
    }
  },
  //猜你喜欢
  async getLike (){
    let data={}
    data['flag'] = 'recommend_activity'
    data['page'] =1
    data['pagesize'] = 10
    data['cityName'] = this.data.currcity
    data['lng'] = app.globalData.currpoint.longitude
    data['lat'] = app.globalData.currpoint.latitude
    const {recode, result, message} = await api.send(data)
    if(recode === 'SUCC') {
      result.forEach((item,index) => {
        item.picurl[0] = this.loadImg(item.picurl[0])
      })
      this.setData({
        likelist:result,
      })
    
    }else {
      this.setData({
        likelist:[],
      })
      // Toast(message)
    }
  },
  //图片加载
  loadImg(img){
    let url =  api.checkurl(img)
    return url
  },

  query(){
    this.getSearch()
    this.getBanner()
    this.getSiging()
    this.getLike()
    this.getHot() 
  },

  onLoad: function () {
    let _this = this
    if( app.globalData.addrList.length==0 )
    this.getAddress()
    else 
    this.setData({items: app.globalData.addrList})    

  },
  
  getlocation(){
    let _this = this;
    wx.getSetting({
      success: res => {
        if (!res.authSetting['scope.userLocation']) {
          wx.authorize({
            scope: 'scope.userLocation',
            success () {
              api.getloc(()=>{
                _this.setData({currcity:app.globalData.address.city})
                _this.query()
              },()=>{
                _this.query()
              })
            },
            fail(){
              _this.query()
            }
          })
        }else{
          api.getloc(()=>{
            _this.setData({currcity:app.globalData.address.city})
            _this.query()
          },()=>{
            _this.query()
          })
        }
      },
      fail: error => {
        console.log(error);
      }
    })
  },

  onShow(e){
  // wx.hideTabBar()

  if( app.globalData.firstflag==1 ){
    app.globalData.firstflag = 0
    this.getlocation()
  }else{
    this.setData({currcity:app.globalData.address.city})
    this.query()
  }
  
	this.setData({
      mainActiveIndex: app.globalData.firstAreaId,activeId:app.globalData.firstAreaId
    });
    setTimeout(()=>{
      let areadata = app.globalData.addrList
      let city = app.globalData.address.city||''
      if( city )
      areadata.forEach((item)=>{
        if( city.indexOf(item.text)>-1 ){
          app.globalData.firstAreaId = item.id
        }
        let citys = item.children||[]
        citys.forEach((item1)=>{
          if( city.indexOf(item1.text)>-1 ){
            app.globalData.firstAreaId = item1.id
          }
        })
      })
    },10000)
  }
})
